/**
 * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.crossriver.crgis.database.service.persistence;

import com.crossriver.crgis.database.NoSuchDocumentsException;
import com.crossriver.crgis.database.model.Documents;
import com.crossriver.crgis.database.model.impl.DocumentsImpl;
import com.crossriver.crgis.database.model.impl.DocumentsModelImpl;

import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.annotation.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * The persistence implementation for the documents service.
 *
 * <p>
 * Never modify or reference this class directly. Always use {@link DocumentsUtil} to access the documents persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
 * </p>
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Wole Adetiba
 * @see DocumentsPersistence
 * @see DocumentsUtil
 * @generated
 */
public class DocumentsPersistenceImpl extends BasePersistenceImpl<Documents>
	implements DocumentsPersistence {
	public static final String FINDER_CLASS_NAME_ENTITY = DocumentsImpl.class.getName();
	public static final String FINDER_CLASS_NAME_LIST = FINDER_CLASS_NAME_ENTITY +
		".List";
	public static final FinderPath FINDER_PATH_FIND_BY_USERID = new FinderPath(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findByUserId",
			new String[] {
				String.class.getName(),
				
			"java.lang.Integer", "java.lang.Integer",
				"com.liferay.portal.kernel.util.OrderByComparator"
			});
	public static final FinderPath FINDER_PATH_COUNT_BY_USERID = new FinderPath(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countByUserId", new String[] { String.class.getName() });
	public static final FinderPath FINDER_PATH_FIND_BY_APPLICATIONID = new FinderPath(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findByApplicationId",
			new String[] {
				String.class.getName(),
				
			"java.lang.Integer", "java.lang.Integer",
				"com.liferay.portal.kernel.util.OrderByComparator"
			});
	public static final FinderPath FINDER_PATH_COUNT_BY_APPLICATIONID = new FinderPath(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countByApplicationId", new String[] { String.class.getName() });
	public static final FinderPath FINDER_PATH_FIND_ALL = new FinderPath(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"findAll", new String[0]);
	public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsModelImpl.FINDER_CACHE_ENABLED, FINDER_CLASS_NAME_LIST,
			"countAll", new String[0]);

	/**
	 * Caches the documents in the entity cache if it is enabled.
	 *
	 * @param documents the documents to cache
	 */
	public void cacheResult(Documents documents) {
		EntityCacheUtil.putResult(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsImpl.class, documents.getPrimaryKey(), documents);
	}

	/**
	 * Caches the documentses in the entity cache if it is enabled.
	 *
	 * @param documentses the documentses to cache
	 */
	public void cacheResult(List<Documents> documentses) {
		for (Documents documents : documentses) {
			if (EntityCacheUtil.getResult(
						DocumentsModelImpl.ENTITY_CACHE_ENABLED,
						DocumentsImpl.class, documents.getPrimaryKey(), this) == null) {
				cacheResult(documents);
			}
		}
	}

	/**
	 * Clears the cache for all documentses.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache() {
		CacheRegistryUtil.clear(DocumentsImpl.class.getName());
		EntityCacheUtil.clearCache(DocumentsImpl.class.getName());
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);
	}

	/**
	 * Clears the cache for the documents.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	public void clearCache(Documents documents) {
		EntityCacheUtil.removeResult(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsImpl.class, documents.getPrimaryKey());
	}

	/**
	 * Creates a new documents with the primary key. Does not add the documents to the database.
	 *
	 * @param documentId the primary key for the new documents
	 * @return the new documents
	 */
	public Documents create(String documentId) {
		Documents documents = new DocumentsImpl();

		documents.setNew(true);
		documents.setPrimaryKey(documentId);

		return documents;
	}

	/**
	 * Removes the documents with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param primaryKey the primary key of the documents to remove
	 * @return the documents that was removed
	 * @throws com.liferay.portal.NoSuchModelException if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents remove(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return remove((String)primaryKey);
	}

	/**
	 * Removes the documents with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param documentId the primary key of the documents to remove
	 * @return the documents that was removed
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents remove(String documentId)
		throws NoSuchDocumentsException, SystemException {
		Session session = null;

		try {
			session = openSession();

			Documents documents = (Documents)session.get(DocumentsImpl.class,
					documentId);

			if (documents == null) {
				if (_log.isWarnEnabled()) {
					_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + documentId);
				}

				throw new NoSuchDocumentsException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
					documentId);
			}

			return remove(documents);
		}
		catch (NoSuchDocumentsException nsee) {
			throw nsee;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Documents removeImpl(Documents documents)
		throws SystemException {
		documents = toUnwrappedModel(documents);

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.delete(session, documents);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		EntityCacheUtil.removeResult(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsImpl.class, documents.getPrimaryKey());

		return documents;
	}

	public Documents updateImpl(
		com.crossriver.crgis.database.model.Documents documents, boolean merge)
		throws SystemException {
		documents = toUnwrappedModel(documents);

		Session session = null;

		try {
			session = openSession();

			BatchSessionUtil.update(session, documents, merge);

			documents.setNew(false);
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST);

		EntityCacheUtil.putResult(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
			DocumentsImpl.class, documents.getPrimaryKey(), documents);

		return documents;
	}

	protected Documents toUnwrappedModel(Documents documents) {
		if (documents instanceof DocumentsImpl) {
			return documents;
		}

		DocumentsImpl documentsImpl = new DocumentsImpl();

		documentsImpl.setNew(documents.isNew());
		documentsImpl.setPrimaryKey(documents.getPrimaryKey());

		documentsImpl.setDocumentId(documents.getDocumentId());
		documentsImpl.setUserId(documents.getUserId());
		documentsImpl.setApplicationId(documents.getApplicationId());
		documentsImpl.setDocumentUpload(documents.getDocumentUpload());

		return documentsImpl;
	}

	/**
	 * Finds the documents with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
	 *
	 * @param primaryKey the primary key of the documents to find
	 * @return the documents
	 * @throws com.liferay.portal.NoSuchModelException if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents findByPrimaryKey(Serializable primaryKey)
		throws NoSuchModelException, SystemException {
		return findByPrimaryKey((String)primaryKey);
	}

	/**
	 * Finds the documents with the primary key or throws a {@link com.crossriver.crgis.database.NoSuchDocumentsException} if it could not be found.
	 *
	 * @param documentId the primary key of the documents to find
	 * @return the documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents findByPrimaryKey(String documentId)
		throws NoSuchDocumentsException, SystemException {
		Documents documents = fetchByPrimaryKey(documentId);

		if (documents == null) {
			if (_log.isWarnEnabled()) {
				_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + documentId);
			}

			throw new NoSuchDocumentsException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
				documentId);
		}

		return documents;
	}

	/**
	 * Finds the documents with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param primaryKey the primary key of the documents to find
	 * @return the documents, or <code>null</code> if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents fetchByPrimaryKey(Serializable primaryKey)
		throws SystemException {
		return fetchByPrimaryKey((String)primaryKey);
	}

	/**
	 * Finds the documents with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param documentId the primary key of the documents to find
	 * @return the documents, or <code>null</code> if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents fetchByPrimaryKey(String documentId)
		throws SystemException {
		Documents documents = (Documents)EntityCacheUtil.getResult(DocumentsModelImpl.ENTITY_CACHE_ENABLED,
				DocumentsImpl.class, documentId, this);

		if (documents == null) {
			Session session = null;

			try {
				session = openSession();

				documents = (Documents)session.get(DocumentsImpl.class,
						documentId);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (documents != null) {
					cacheResult(documents);
				}

				closeSession(session);
			}
		}

		return documents;
	}

	/**
	 * Finds all the documentses where userId = &#63;.
	 *
	 * @param userId the user id to search with
	 * @return the matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findByUserId(String userId)
		throws SystemException {
		return findByUserId(userId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the documentses where userId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param userId the user id to search with
	 * @param start the lower bound of the range of documentses to return
	 * @param end the upper bound of the range of documentses to return (not inclusive)
	 * @return the range of matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findByUserId(String userId, int start, int end)
		throws SystemException {
		return findByUserId(userId, start, end, null);
	}

	/**
	 * Finds an ordered range of all the documentses where userId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param userId the user id to search with
	 * @param start the lower bound of the range of documentses to return
	 * @param end the upper bound of the range of documentses to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findByUserId(String userId, int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				userId,
				
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<Documents> list = (List<Documents>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_USERID,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(3 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(3);
			}

			query.append(_SQL_SELECT_DOCUMENTS_WHERE);

			if (userId == null) {
				query.append(_FINDER_COLUMN_USERID_USERID_1);
			}
			else {
				if (userId.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_USERID_USERID_3);
				}
				else {
					query.append(_FINDER_COLUMN_USERID_USERID_2);
				}
			}

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}

			else {
				query.append(DocumentsModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (userId != null) {
					qPos.add(userId);
				}

				list = (List<Documents>)QueryUtil.list(q, getDialect(), start,
						end);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FIND_BY_USERID,
						finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_USERID,
						finderArgs, list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Finds the first documents in the ordered set where userId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param userId the user id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the first matching documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a matching documents could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents findByUserId_First(String userId,
		OrderByComparator orderByComparator)
		throws NoSuchDocumentsException, SystemException {
		List<Documents> list = findByUserId(userId, 0, 1, orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("userId=");
			msg.append(userId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchDocumentsException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the last documents in the ordered set where userId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param userId the user id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the last matching documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a matching documents could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents findByUserId_Last(String userId,
		OrderByComparator orderByComparator)
		throws NoSuchDocumentsException, SystemException {
		int count = countByUserId(userId);

		List<Documents> list = findByUserId(userId, count - 1, count,
				orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("userId=");
			msg.append(userId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchDocumentsException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the documentses before and after the current documents in the ordered set where userId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param documentId the primary key of the current documents
	 * @param userId the user id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the previous, current, and next documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents[] findByUserId_PrevAndNext(String documentId,
		String userId, OrderByComparator orderByComparator)
		throws NoSuchDocumentsException, SystemException {
		Documents documents = findByPrimaryKey(documentId);

		Session session = null;

		try {
			session = openSession();

			Documents[] array = new DocumentsImpl[3];

			array[0] = getByUserId_PrevAndNext(session, documents, userId,
					orderByComparator, true);

			array[1] = documents;

			array[2] = getByUserId_PrevAndNext(session, documents, userId,
					orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Documents getByUserId_PrevAndNext(Session session,
		Documents documents, String userId,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_DOCUMENTS_WHERE);

		if (userId == null) {
			query.append(_FINDER_COLUMN_USERID_USERID_1);
		}
		else {
			if (userId.equals(StringPool.BLANK)) {
				query.append(_FINDER_COLUMN_USERID_USERID_3);
			}
			else {
				query.append(_FINDER_COLUMN_USERID_USERID_2);
			}
		}

		if (orderByComparator != null) {
			String[] orderByFields = orderByComparator.getOrderByFields();

			if (orderByFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}

		else {
			query.append(DocumentsModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		if (userId != null) {
			qPos.add(userId);
		}

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByValues(documents);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Documents> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Finds all the documentses where applicationId = &#63;.
	 *
	 * @param applicationId the application id to search with
	 * @return the matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findByApplicationId(String applicationId)
		throws SystemException {
		return findByApplicationId(applicationId, QueryUtil.ALL_POS,
			QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the documentses where applicationId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param applicationId the application id to search with
	 * @param start the lower bound of the range of documentses to return
	 * @param end the upper bound of the range of documentses to return (not inclusive)
	 * @return the range of matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findByApplicationId(String applicationId, int start,
		int end) throws SystemException {
		return findByApplicationId(applicationId, start, end, null);
	}

	/**
	 * Finds an ordered range of all the documentses where applicationId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param applicationId the application id to search with
	 * @param start the lower bound of the range of documentses to return
	 * @param end the upper bound of the range of documentses to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findByApplicationId(String applicationId, int start,
		int end, OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				applicationId,
				
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<Documents> list = (List<Documents>)FinderCacheUtil.getResult(FINDER_PATH_FIND_BY_APPLICATIONID,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(3 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(3);
			}

			query.append(_SQL_SELECT_DOCUMENTS_WHERE);

			if (applicationId == null) {
				query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_1);
			}
			else {
				if (applicationId.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_3);
				}
				else {
					query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_2);
				}
			}

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}

			else {
				query.append(DocumentsModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (applicationId != null) {
					qPos.add(applicationId);
				}

				list = (List<Documents>)QueryUtil.list(q, getDialect(), start,
						end);
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FIND_BY_APPLICATIONID,
						finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(FINDER_PATH_FIND_BY_APPLICATIONID,
						finderArgs, list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Finds the first documents in the ordered set where applicationId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param applicationId the application id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the first matching documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a matching documents could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents findByApplicationId_First(String applicationId,
		OrderByComparator orderByComparator)
		throws NoSuchDocumentsException, SystemException {
		List<Documents> list = findByApplicationId(applicationId, 0, 1,
				orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("applicationId=");
			msg.append(applicationId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchDocumentsException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the last documents in the ordered set where applicationId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param applicationId the application id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the last matching documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a matching documents could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents findByApplicationId_Last(String applicationId,
		OrderByComparator orderByComparator)
		throws NoSuchDocumentsException, SystemException {
		int count = countByApplicationId(applicationId);

		List<Documents> list = findByApplicationId(applicationId, count - 1,
				count, orderByComparator);

		if (list.isEmpty()) {
			StringBundler msg = new StringBundler(4);

			msg.append(_NO_SUCH_ENTITY_WITH_KEY);

			msg.append("applicationId=");
			msg.append(applicationId);

			msg.append(StringPool.CLOSE_CURLY_BRACE);

			throw new NoSuchDocumentsException(msg.toString());
		}
		else {
			return list.get(0);
		}
	}

	/**
	 * Finds the documentses before and after the current documents in the ordered set where applicationId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param documentId the primary key of the current documents
	 * @param applicationId the application id to search with
	 * @param orderByComparator the comparator to order the set by
	 * @return the previous, current, and next documents
	 * @throws com.crossriver.crgis.database.NoSuchDocumentsException if a documents with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	public Documents[] findByApplicationId_PrevAndNext(String documentId,
		String applicationId, OrderByComparator orderByComparator)
		throws NoSuchDocumentsException, SystemException {
		Documents documents = findByPrimaryKey(documentId);

		Session session = null;

		try {
			session = openSession();

			Documents[] array = new DocumentsImpl[3];

			array[0] = getByApplicationId_PrevAndNext(session, documents,
					applicationId, orderByComparator, true);

			array[1] = documents;

			array[2] = getByApplicationId_PrevAndNext(session, documents,
					applicationId, orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Documents getByApplicationId_PrevAndNext(Session session,
		Documents documents, String applicationId,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_DOCUMENTS_WHERE);

		if (applicationId == null) {
			query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_1);
		}
		else {
			if (applicationId.equals(StringPool.BLANK)) {
				query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_3);
			}
			else {
				query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_2);
			}
		}

		if (orderByComparator != null) {
			String[] orderByFields = orderByComparator.getOrderByFields();

			if (orderByFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}

		else {
			query.append(DocumentsModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		if (applicationId != null) {
			qPos.add(applicationId);
		}

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByValues(documents);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Documents> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Finds all the documentses.
	 *
	 * @return the documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findAll() throws SystemException {
		return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Finds a range of all the documentses.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of documentses to return
	 * @param end the upper bound of the range of documentses to return (not inclusive)
	 * @return the range of documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findAll(int start, int end)
		throws SystemException {
		return findAll(start, end, null);
	}

	/**
	 * Finds an ordered range of all the documentses.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
	 * </p>
	 *
	 * @param start the lower bound of the range of documentses to return
	 * @param end the upper bound of the range of documentses to return (not inclusive)
	 * @param orderByComparator the comparator to order the results by
	 * @return the ordered range of documentses
	 * @throws SystemException if a system exception occurred
	 */
	public List<Documents> findAll(int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		Object[] finderArgs = new Object[] {
				String.valueOf(start), String.valueOf(end),
				String.valueOf(orderByComparator)
			};

		List<Documents> list = (List<Documents>)FinderCacheUtil.getResult(FINDER_PATH_FIND_ALL,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;
			String sql = null;

			if (orderByComparator != null) {
				query = new StringBundler(2 +
						(orderByComparator.getOrderByFields().length * 3));

				query.append(_SQL_SELECT_DOCUMENTS);

				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);

				sql = query.toString();
			}
			else {
				sql = _SQL_SELECT_DOCUMENTS.concat(DocumentsModelImpl.ORDER_BY_JPQL);
			}

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				if (orderByComparator == null) {
					list = (List<Documents>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);
				}
				else {
					list = (List<Documents>)QueryUtil.list(q, getDialect(),
							start, end);
				}
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (list == null) {
					FinderCacheUtil.removeResult(FINDER_PATH_FIND_ALL,
						finderArgs);
				}
				else {
					cacheResult(list);

					FinderCacheUtil.putResult(FINDER_PATH_FIND_ALL, finderArgs,
						list);
				}

				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Removes all the documentses where userId = &#63; from the database.
	 *
	 * @param userId the user id to search with
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByUserId(String userId) throws SystemException {
		for (Documents documents : findByUserId(userId)) {
			remove(documents);
		}
	}

	/**
	 * Removes all the documentses where applicationId = &#63; from the database.
	 *
	 * @param applicationId the application id to search with
	 * @throws SystemException if a system exception occurred
	 */
	public void removeByApplicationId(String applicationId)
		throws SystemException {
		for (Documents documents : findByApplicationId(applicationId)) {
			remove(documents);
		}
	}

	/**
	 * Removes all the documentses from the database.
	 *
	 * @throws SystemException if a system exception occurred
	 */
	public void removeAll() throws SystemException {
		for (Documents documents : findAll()) {
			remove(documents);
		}
	}

	/**
	 * Counts all the documentses where userId = &#63;.
	 *
	 * @param userId the user id to search with
	 * @return the number of matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public int countByUserId(String userId) throws SystemException {
		Object[] finderArgs = new Object[] { userId };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_USERID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_DOCUMENTS_WHERE);

			if (userId == null) {
				query.append(_FINDER_COLUMN_USERID_USERID_1);
			}
			else {
				if (userId.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_USERID_USERID_3);
				}
				else {
					query.append(_FINDER_COLUMN_USERID_USERID_2);
				}
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (userId != null) {
					qPos.add(userId);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_USERID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Counts all the documentses where applicationId = &#63;.
	 *
	 * @param applicationId the application id to search with
	 * @return the number of matching documentses
	 * @throws SystemException if a system exception occurred
	 */
	public int countByApplicationId(String applicationId)
		throws SystemException {
		Object[] finderArgs = new Object[] { applicationId };

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_APPLICATIONID,
				finderArgs, this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_DOCUMENTS_WHERE);

			if (applicationId == null) {
				query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_1);
			}
			else {
				if (applicationId.equals(StringPool.BLANK)) {
					query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_3);
				}
				else {
					query.append(_FINDER_COLUMN_APPLICATIONID_APPLICATIONID_2);
				}
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				if (applicationId != null) {
					qPos.add(applicationId);
				}

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_APPLICATIONID,
					finderArgs, count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Counts all the documentses.
	 *
	 * @return the number of documentses
	 * @throws SystemException if a system exception occurred
	 */
	public int countAll() throws SystemException {
		Object[] finderArgs = new Object[0];

		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
				finderArgs, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(_SQL_COUNT_DOCUMENTS);

				count = (Long)q.uniqueResult();
			}
			catch (Exception e) {
				throw processException(e);
			}
			finally {
				if (count == null) {
					count = Long.valueOf(0);
				}

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL, finderArgs,
					count);

				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Initializes the documents persistence.
	 */
	public void afterPropertiesSet() {
		String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
					com.liferay.util.service.ServiceProps.get(
						"value.object.listener.com.crossriver.crgis.database.model.Documents")));

		if (listenerClassNames.length > 0) {
			try {
				List<ModelListener<Documents>> listenersList = new ArrayList<ModelListener<Documents>>();

				for (String listenerClassName : listenerClassNames) {
					listenersList.add((ModelListener<Documents>)InstanceFactory.newInstance(
							listenerClassName));
				}

				listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
			}
			catch (Exception e) {
				_log.error(e);
			}
		}
	}

	public void destroy() {
		EntityCacheUtil.removeCache(DocumentsImpl.class.getName());
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST);
	}

	@BeanReference(type = Application_C_of_OPersistence.class)
	protected Application_C_of_OPersistence application_C_of_OPersistence;
	@BeanReference(type = Supporting_DocumentPersistence.class)
	protected Supporting_DocumentPersistence supporting_DocumentPersistence;
	@BeanReference(type = DocumentsPersistence.class)
	protected DocumentsPersistence documentsPersistence;
	@BeanReference(type = Individual_InformationPersistence.class)
	protected Individual_InformationPersistence individual_InformationPersistence;
	@BeanReference(type = Organisation_InformationPersistence.class)
	protected Organisation_InformationPersistence organisation_InformationPersistence;
	@BeanReference(type = Contact_InformationPersistence.class)
	protected Contact_InformationPersistence contact_InformationPersistence;
	@BeanReference(type = Company_Contact_PersonPersistence.class)
	protected Company_Contact_PersonPersistence company_Contact_PersonPersistence;
	@BeanReference(type = Property_InformationPersistence.class)
	protected Property_InformationPersistence property_InformationPersistence;
	@BeanReference(type = Held_PlotsPersistence.class)
	protected Held_PlotsPersistence held_PlotsPersistence;
	@BeanReference(type = History_Of_InformationPersistence.class)
	protected History_Of_InformationPersistence history_Of_InformationPersistence;
	@BeanReference(type = TransactionsPersistence.class)
	protected TransactionsPersistence transactionsPersistence;
	@BeanReference(type = Bank_Payment_SlipPersistence.class)
	protected Bank_Payment_SlipPersistence bank_Payment_SlipPersistence;
	@BeanReference(type = ResourcePersistence.class)
	protected ResourcePersistence resourcePersistence;
	@BeanReference(type = UserPersistence.class)
	protected UserPersistence userPersistence;
	private static final String _SQL_SELECT_DOCUMENTS = "SELECT documents FROM Documents documents";
	private static final String _SQL_SELECT_DOCUMENTS_WHERE = "SELECT documents FROM Documents documents WHERE ";
	private static final String _SQL_COUNT_DOCUMENTS = "SELECT COUNT(documents) FROM Documents documents";
	private static final String _SQL_COUNT_DOCUMENTS_WHERE = "SELECT COUNT(documents) FROM Documents documents WHERE ";
	private static final String _FINDER_COLUMN_USERID_USERID_1 = "documents.userId IS NULL";
	private static final String _FINDER_COLUMN_USERID_USERID_2 = "documents.userId = ?";
	private static final String _FINDER_COLUMN_USERID_USERID_3 = "(documents.userId IS NULL OR documents.userId = ?)";
	private static final String _FINDER_COLUMN_APPLICATIONID_APPLICATIONID_1 = "documents.applicationId IS NULL";
	private static final String _FINDER_COLUMN_APPLICATIONID_APPLICATIONID_2 = "documents.applicationId = ?";
	private static final String _FINDER_COLUMN_APPLICATIONID_APPLICATIONID_3 = "(documents.applicationId IS NULL OR documents.applicationId = ?)";
	private static final String _ORDER_BY_ENTITY_ALIAS = "documents.";
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Documents exists with the primary key ";
	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Documents exists with the key {";
	private static Log _log = LogFactoryUtil.getLog(DocumentsPersistenceImpl.class);
}